import axios from 'axios';
import base from '_common/services/base';
const apiUrl = base.test;
import { getCookie,setCookie } from '@/utils/cookiesUtil.js'
import {getQuery} from '@/utils/utils'
import getOauth from '_common/getOauth.js'

export default async function wxLogin(getData = ()=> {}) {
    console.log('token ', getCookie('token'));
    if (getCookie('token')) {
        getData();
        return false;
    } else if (getQuery('code') && getQuery('state') && !getCookie('token')){
        await axios({
            url: 'http://www.nineunity.com/nu/anon/user/oauth2/access',
            method: 'post',
            data:{
                code: getQuery('code'),
                state: getQuery('state'),
            },
        }).then(res => {
            console.log('res:', res);
            if (res.data && res.data.code === 0) {
                const { token, weChatUserInfo, hasBind, agencyLevel } =res.data.data;
                const {nickName, headImgUrl } = weChatUserInfo;
                // 把token 和用户信息存在本地
                setCookie('token', token);
                setCookie('nickName', nickName);
                setCookie('headImgUrl', headImgUrl);
                setCookie('agencyLevel', agencyLevel);
                if (!hasBind) {
                    location.href = `${apiUrl}/login.html`;
                }
                getData();
            } else {
                location.href = window.location.href.split('code=')[0].split('state=')[0];
            }
        }).catch(err => {
            console.log('err:', err);
            location.href = window.location.href.split('code=')[0].split('state=')[0];
        })
    } else {
        await getOauth();
    }
}